package org.openea.eap.module.obpm.util.custsql;

import net.sf.jsqlparser.statement.Statement;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.AppUtil;
import org.openbpm.sys.api.service.ISysDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;










public class JdbcTemplateUtil
{
  private static Logger logger = LoggerFactory.getLogger(JdbcTemplateUtil.class);












  public static ResultMsg<String> executeSql(String dsKey, String sql) {
    ResultMsg<Statement> selectSqlRsp = SqlUtil.isSelectSql(sql);
    if (!selectSqlRsp.getIsOk().booleanValue()) {
      logger.error("sql格式不正确,sql:{}", sql);
      return ResultMsg.ERROR(selectSqlRsp.getMsg());
    }

    JdbcTemplate jdbcTemplate = getJdbcTemplate(dsKey);

    try {
      sql = SqlUtil.getNoDataSql(sql);
      jdbcTemplate.execute(sql);
      return ResultMsg.SUCCESS();
    } catch (Exception e) {
      logger.error("执行SQL异常。e:{}", e);
      return ResultMsg.ERROR(e.getMessage());
    }
  }



















  public static NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) { return new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); }












  public static String getDataType(String dataType) {
    String dbType = dataType.toLowerCase();

    String number = "tinyint,bigint,smallint,int,decimal,number,numeric,BIGINT UNSIGNED,bigint unsigned";
    String doubleCol = "double,float";
    String date = "date";
    String datetime = "timestamp,datetime";
    String text = "clob,text";
    String varchar = "varchar,varchar2,char";

    boolean isChar = isSpecType(dbType, varchar);
    if (isChar) {
      return "varchar";
    }

    boolean isNumber = isSpecType(dbType, number);
    if (isNumber) {
      return "number";
    }
    boolean isDouble = isSpecType(dbType, doubleCol);
    if (isDouble) {
      return "double";
    }

    boolean isDate = isSpecType(dbType, date);
    if (isDate) {
      return "date";
    }

    boolean isDateTime = isSpecType(dbType, datetime);
    if (isDateTime) {
      return "datetime";
    }

    boolean isText = isSpecType(dbType, text);
    if (isText) {
      return "text";
    }

    return dbType;
  }









  private static boolean isSpecType(String dbType, String dataType) {
    String[] aryType = dataType.split(",");
    for (String str : aryType) {
      if (dbType.equals(str)) {
        return true;
      }
    }
    return false;
  }

  public static JdbcTemplate getJdbcTemplate(String dsKey) {
    JdbcTemplate jdbcTemplate = ((ISysDataSourceService)AppUtil.getBean(ISysDataSourceService.class)).getJdbcTemplateByKey(dsKey);
    return jdbcTemplate;
  }
}
